package com.zuo.mall.service.impl;

import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zuo.mall.common.api.CommonPage;
import com.zuo.mall.dto.OmsOrderDeliveryParam;
import com.zuo.mall.dto.OmsOrderDetail;
import com.zuo.mall.dto.OmsOrderQueryParam;
import com.zuo.mall.dto.OmsReceiverInfoParam;
import com.zuo.mall.entity.OmsOrder;
import com.zuo.mall.entity.OmsOrderOperateHistory;
import com.zuo.mall.mapper.OmsOrderMapper;
import com.zuo.mall.mapper.OmsOrderOperateHistoryMapper;
import com.zuo.mall.service.OmsOrderOperationHistoryService;
import com.zuo.mall.service.OmsOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements OmsOrderService {

    @Autowired
    private OmsOrderOperateHistoryMapper historyMapper;

    @Autowired
    private OmsOrderOperationHistoryService historyService;

    @Override
    public CommonPage<OmsOrder> getPage(OmsOrderQueryParam orderQueryParam, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<OmsOrder> queryWrapper = new LambdaQueryWrapper<>();


        // 订单号
        if (!StrUtil.isEmpty(orderQueryParam.getOrderSn())) {
            queryWrapper.eq(OmsOrder::getOrderSn, orderQueryParam.getOrderSn());
        }

        // 收货人姓名 号码
        String receiverKeyword = orderQueryParam.getReceiverKeyword();
        if (!StrUtil.isEmpty(receiverKeyword)) {
            queryWrapper.like(OmsOrder::getReceiverName, receiverKeyword)
                    .or().like(OmsOrder::getReceiverPhone, receiverKeyword);
        }

        // 订单状态
        Integer status = orderQueryParam.getStatus();
        if (status != null) {
            queryWrapper.eq(OmsOrder::getStatus, status);
        }

        // 订单类型
        Integer orderType = orderQueryParam.getOrderType();
        if (orderType != null) {
            queryWrapper.eq(OmsOrder::getOrderType, orderType);
        }

        // 订单来源
        Integer sourceType = orderQueryParam.getSourceType();
        if (sourceType != null) {
            queryWrapper.eq(OmsOrder::getSourceType, sourceType);
        }

        // 订单提交时间
        String createTime = orderQueryParam.getCreateTime();
        if (!StrUtil.isEmpty(createTime)) {
            queryWrapper.like(OmsOrder::getCreateTime, "concat(" + createTime + ",'%')");
        }

        Integer total = baseMapper.selectCount(queryWrapper);
//        queryWrapper.select(OmsOrder::getOrderSn,
//                OmsOrder::getId,
//                OmsOrder::getCreateTime,
//                OmsOrder::getMemberUsername,
//                OmsOrder::getTotalAmount,
//                OmsOrder::getPayType,
//                OmsOrder::getSourceType,
//                OmsOrder::getOrderType);

        queryWrapper.last("LIMIT " + PageUtil.getStart(pageNum - 1, pageSize) + "," + pageSize);
        List<OmsOrder> omsOrders = baseMapper.selectList(queryWrapper);
        CommonPage<OmsOrder> omsOrderCommonPage = CommonPage.restPage(omsOrders, Long.valueOf(total), pageSize);

        return omsOrderCommonPage;
    }

    @Override
    public OmsOrderDetail getOrderDetailById(Long id) {

        return baseMapper.selectDetailById(id);

    }

    @Transactional
    @Override
    public int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) {
        OmsOrder omsOrder = new OmsOrder();
        BeanUtils.copyProperties(receiverInfoParam, omsOrder);
        omsOrder.setId(receiverInfoParam.getOrderId());
        int count = baseMapper.updateById(omsOrder);
        // 修改完成插入记录
        OmsOrderOperateHistory omsOrderOperateHistory = new OmsOrderOperateHistory();
        omsOrderOperateHistory.setOrderId(omsOrder.getId());
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String name = authentication.getName();
        omsOrderOperateHistory.setOperateMan(name);
        omsOrderOperateHistory.setOrderStatus(omsOrder.getStatus());
        omsOrderOperateHistory.setCreateTime(LocalDateTime.now());
        omsOrderOperateHistory.setNote("修改收货人信息");
        historyMapper.insert(omsOrderOperateHistory);
        return count;
    }

    @Transactional
    @Override
    public int updateNoteById(Long id, String note, Integer status) {
        LambdaUpdateWrapper<OmsOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(OmsOrder::getNote, note);
        updateWrapper.eq(OmsOrder::getId, id);

        // 修改成功添加记录
        boolean update = this.update(updateWrapper);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderStatus(status);
        history.setOrderId(id);
        history.setCreateTime(LocalDateTime.now());
        history.setOperateMan(SecurityContextHolder.getContext().getAuthentication().getName());
        history.setNote("修改备注: "+ note);
        historyMapper.insert(history);
        return update ? 1 : 0;
    }

    @Transactional
    @Override
    public int closeOrderBatch(List<Long> ids, String note) {
        LambdaUpdateWrapper<OmsOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(OmsOrder::getStatus, 4);
        updateWrapper.in(OmsOrder::getId, ids);
        boolean update = this.update(updateWrapper);
        if (!update) throw new RuntimeException("关闭订单异常");

        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        List<OmsOrderOperateHistory> historyList = ids.stream().map(id -> {
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderStatus(4);
            history.setOrderId(id);
            history.setCreateTime(LocalDateTime.now());
            history.setOperateMan(name);
            history.setNote("订单关闭: " + note);
            return history;
        }).collect(Collectors.toList());

        historyService.saveBatch(historyList);
        return 1;
    }

    @Override
    public int deleteOrderBatch(List<Long> ids) {
        LambdaUpdateWrapper<OmsOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(OmsOrder::getDeleteStatus, 1);
        updateWrapper.in(OmsOrder::getId, ids);
        boolean update = this.update(updateWrapper);
        return update?ids.size():0;
    }

    @Override
    public int deliveryBatch(List<OmsOrderDeliveryParam> deliveryParams) {
        baseMapper.deliveryBatch(deliveryParams);
        return 1;
    }
}
